import pandas as pd
import numpy as np
from sklearn.ensemble import RandomForestRegressor
from scipy.optimize import minimize
import matplotlib.pyplot as plt
from pyswarm import pso  # For particle swarm optimization

# 读取数据
data = pd.read_excel('合并数据集.xlsx')
data = data.iloc[1:]  # 删除第一行
plt.rcParams['font.sans-serif'] = ['SimHei']  # 使用SimHei字体
plt.rcParams['axes.unicode_minus'] = False  # 正确显示负号
# 提取特征和目标
material = pd.Categorical(data.iloc[:, 0]).codes  # 材料
temperature = data.iloc[:, 1].values  # 温度
frequency = data.iloc[:, 2].values  # 频率
core_loss = data.iloc[:, 3].values  # 磁芯损耗
waveform = pd.Categorical(data.iloc[:, 4]).codes  # 励磁波形
magnetic_density = data.iloc[:, 5:].values  # 磁通密度数据

# 磁通密度峰值
Bm = np.max(magnetic_density, axis=1)

# 构建输入特征矩阵
X = np.column_stack((material, temperature, frequency, waveform, Bm))

# 构建随机森林模型
model = RandomForestRegressor(n_estimators=100, random_state=1)
model.fit(X, core_loss)

# 计算传输磁能
transmission_energy_values = frequency * Bm

# 计算均值和标准差
mean_core_loss = np.mean(core_loss)
std_core_loss = np.std(core_loss)
mean_trans_energy = np.mean(transmission_energy_values)
std_trans_energy = np.std(transmission_energy_values)

# 计算变异系数
cv_core_loss = std_core_loss / mean_core_loss
cv_trans_energy = std_trans_energy / mean_trans_energy

# 权重计算
w1 = 1 / cv_core_loss
w2 = 1 / cv_trans_energy

# 归一化权重
w_sum = w1 + w2
w1 /= w_sum
w2 /= w_sum

# 输出权重
print('基于变异系数的权重:')
print(f'磁芯损耗权重: {w1:.4f}')
print(f'传输磁能权重: {w2:.4f}')

# 定义目标函数
def objective(x):
    return w1 * model.predict([x]) + w2 * (-x[2] * x[4])  # x[2] 是频率, x[4] 是 Bm

# 定义优化变量的上下界
lb = [0, 25, 50000, 0, 0]  # 下界
ub = [3, 90, 500000, 2, np.max(Bm)]  # 上界

# 粒子群算法进行优化
xopt, fopt = pso(objective, lb, ub)

# 输出优化结果
print(f'最优材料: 材料{round(xopt[0])}')
print(f'最优温度: {xopt[1]:.2f}摄氏度')
print(f'最优频率: {xopt[2]:.2f}Hz')
print(f'最优波形类型: 波形{round(xopt[3])}')
print(f'最优磁通密度峰值: {xopt[4]:.4f}T')

# 最优传输磁能
optimal_transmission_energy = xopt[2] * xopt[4]
print(f'最优传输磁能: {optimal_transmission_energy:.4f}')

# 最小磁芯损耗
optimal_core_loss = model.predict([xopt])
print(f'最小磁芯损耗: {optimal_core_loss[0]:.4f}W/m^3')

# 可视化磁芯损耗和传输磁能的变化情况
plt.figure(figsize=(12, 6))

# 子图1：磁芯损耗变化情况
plt.subplot(1, 2, 1)
plt.plot(core_loss, 'r-', linewidth=1.5)
plt.xlabel('样本编号')
plt.ylabel('磁芯损耗 (W/m^3)')
plt.title('磁芯损耗变化')
plt.grid()

# 子图2：传输磁能变化情况
plt.subplot(1, 2, 2)
plt.plot(transmission_energy_values, 'b-', linewidth=1.5)
plt.xlabel('样本编号')
plt.ylabel('传输磁能')
plt.title('传输磁能变化')
plt.grid()

plt.tight_layout()
plt.show()
